package servletsWithoutStruts;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import domain.Contact;
import domain.DAOContact;
import domain.IDAOContact;

/**
 * Servlet implementation class FindContactServlet
 */
public class FindContactServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FindContactServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
		IDAOContact dao = (IDAOContact) context.getBean("daocontact");
		String findBy = request.getParameter("findBy");
		ArrayList<Contact> foundContacts = new ArrayList<Contact>();
		if ( findBy.equals("email"))
		{
			String email  =  request.getParameter("email");
			foundContacts = dao.getContactByEmail(email);
		}
		else if(findBy.equals("firstName"))
		{
			String firstName = request.getParameter("firstName");
			foundContacts = dao.getContactByFirstName(firstName);
		}
		else
		{
			String lastName  =  request.getParameter("lastName");
			foundContacts = dao.getContactByLastName(lastName);
		}
		request.setAttribute("contacts", foundContacts.toArray());
		RequestDispatcher reqDispatcher = request.getRequestDispatcher("indexContacts.jsp");
	    reqDispatcher.forward(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
